import React, { Component } from 'react';
import { Card, Tabs, Upload, Button, Form, Modal, Input, Icon, message, Select, Divider, Row, Col } from 'antd';
import styles from './index.less';
// import Tiptap from './Tiptap';
import { postSaveTemplate } from '@/services/modelInstruction';
import { getModelList, getAgentInfo, postAgentAdd, postAgentEdit, postGenerateSettings } from '@/services/assistantCenter';
import Editor from '@/utils/Editor';

class AddAgent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            avatar: "",
            loading: false,
            assistantInfo: null,
            assistantVisible: false,

            id: null,
            questionCount: 1,
            modelCount: 1,
            modelList: [],

            generateLoading: false,
        };
        // this.ProsemirrorEditorRef = React.createRef();
    }

    componentDidMount() {
        if (this.props.onRef) {
            this.props.onRef(this)
        }
    }

    _init_ = id => {
        if (id) {
            this.agentInfo(id)
        };
        this.setState({ assistantVisible: true, id }, () => {
            this.getModelData();
        })
    }

    agentInfo = async id => {
        const { form } = this.props;
        let res = await getAgentInfo({ id });
        console.log(res);
        this.setState({ assistantInfo: res, avatar: res.avatar, questionCount: res.questionList.length, modelCount: res.modelList && res.modelList.length > 0 ? res.modelList.length : 1 });
    }

    getModelData = async () => {
        let res = await getModelList();
        console.log(res);
        this.setState({ modelList: res });
    }

    assistantCancel = () => {
        this.setState({
            avatar: "",
            loading: false,
            assistantInfo: null,
            assistantVisible: false,

            id: null,
            questionCount: 1,
            modelCount: 1,
            modelList: [],
        })
    }

    assistantSubmit = () => {
        const { id, avatar, assistantInfo } = this.state;
        const { form, categoryKey } = this.props;
        let obj, res = { code: -1, data: false, mag: "操作失败" };
        let formInfo = form.getFieldsValue();
        form.validateFields(async (err, values) => {
            if (!err) {
                obj = { ...formInfo };
                if (avatar && avatar !== '') {
                    obj.avatar = avatar;
                } else {
                    form.setFields({ avatar: { errors: [new Error('指令图片必填')], } });
                    return;
                };
                obj.modelIdList = obj.modelIdList.filter(item => item);
                const welcomeTxt = this.ueditor.getUeditorContent();
                if(welcomeTxt === '' || welcomeTxt === null || welcomeTxt === undefined){
                  message.error('请输入助手欢迎语')
                  return false;
                }
                obj.welcomeTxt = welcomeTxt
                if (obj && obj.modelIdList && obj.modelIdList.length > 0) {
                    if (id) {
                        obj.id = id;
                        res = await postAgentEdit(obj);
                    } else {
                        res = await postAgentAdd(obj);
                    };
                } else {
                    return message.error('请选择至少一个大模型！！');
                };
                console.log(res);

                

                if (res.code === 0) {
                    this.props.getList(categoryKey, 1);
                    this.assistantCancel();
                    message.success('操作成功');
                }
            }
        })
    }

    render() {
        const { assistantVisible, assistantInfo, avatar, generateLoading } = this.state;
        const { categoryList, categoryId } = this.props;
        const { getFieldDecorator } = this.props.form;
        const uploadButton = (
            <div style={{ border: '#E8E8E8 1px solid', padding: '14px 7px', textAlign: 'center', background: '#FAFAFA', }}>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">上传文件</div>
            </div>
        );

        return (
            <Modal
                title="创建助手"
                onCancel={this.assistantCancel}
                visible={assistantVisible}
                footer={assistantInfo?.sysShare ? false : [
                    <Button onClick={this.assistantCancel}>取消</Button>,
                    <Button type="primary" onClick={this.assistantSubmit}>确定</Button>
                ]}
                centered
                width={'800px'}
                destroyOnClose
            >
                <Form>
                    <div style={{ display: 'flex', width: '100%', gap: '16px' }}>
                        <Form.Item label="助手名称" style={{ width: '50%', marginBottom: 8 }}>
                            {getFieldDecorator('name', {
                                initialValue: assistantInfo?.name,
                                rules: [{ required: true, message: '助手名称必填' }],
                            })(<Input placeholder="请输入助手名称" />)}
                        </Form.Item>
                        {assistantInfo?.sysShare ? null : (
                            <Form.Item label="助手分类" style={{ width: '50%', marginBottom: 8 }}>
                                {getFieldDecorator('categoryId', {
                                    initialValue: assistantInfo ? assistantInfo.categoryId : categoryId && categoryId !== '' ? categoryId : undefined,
                                    rules: [{ required: true, message: '助手分类必填' }],
                                })(
                                    <Select placeholder="选择/修改分类">
                                        {categoryList && categoryList.length > 0 && categoryList.map(item => {
                                            return (
                                                <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                            );
                                        })}
                                    </Select>
                                )}
                            </Form.Item>
                        )}
                    </div>

                    <div style={{ display: 'flex', width: '100%', gap: '16px' }}>
                        <Form.Item label="助手简介" style={{ width: '75%', marginBottom: 8 }}>
                            {getFieldDecorator('introduction', {
                                initialValue: assistantInfo?.introduction,
                            })(<Input.TextArea rows={3} placeholder="请输入助手简介" />)}
                        </Form.Item>
                        
                        <Form.Item label='助手头像' style={{ marginBottom: 8 }}>
                            <span className={styles['default-img-ul']}>
                                {getFieldDecorator("avatar", {
                                    initialValue: assistantInfo?.avatar,
                                    valuePropName: "url",
                                    rules: [{ required: true }],
                                    getValueFromEvent: this.normFile,
                                })(
                                    <Upload
                                        name='file'
                                        listType='picture'
                                        showUploadList={false}
                                        action='/cloud/file/upload'
                                        beforeUpload={this.beforeUpload}
                                        onChange={(info) => this.handleChangeImage(info, "avatar")}
                                        accept='.png,.jpg,.gif,.svg'
                                    >
                                        {avatar && avatar !== '' ? (
                                            <div
                                                style={{
                                                    width: '72px',
                                                    height: '72px',
                                                    fontSize: '0px',
                                                    lineHeight: '72px',
                                                    textAlign: 'center',
                                                    border: '#3e5bff 1px solid',
                                                    background: '#f0f5ff',
                                                }}
                                            >
                                                <img src={fileUrl + avatar} alt='file' style={{ maxWidth: 70, maxHeight: 70 }} />
                                            </div>
                                        ) : uploadButton}
                                    </Upload>
                                )}
                            </span>
                        </Form.Item>
                    </div>

                    <div>
                      <Form.Item label="助手欢迎语" style={{ width: '75%', marginBottom: 8 }}>
                        <Editor
                          content={assistantInfo?.welcomeTxt}
                          name="content"
                          id="content"
                          width="300"
                          ref={r => (this.ueditor = r)}
                        />
                      </Form.Item>
                    </div>

                    <Divider dashed style={{ margin: '16px 0' }} />

                    <Form.Item label="角色设定" style={{ width: '100%', marginBottom: 8 }}>
                        {getFieldDecorator('characterSetting', {
                            initialValue: assistantInfo?.characterSetting,
                        })(<Input.TextArea rows={3} />)}
                        <Row gutter={[16, 16]}>
                            <Col span={24} style={{ textAlign: 'right' }}>
                                <Button onClick={this.getGenerateQuestion} loading={generateLoading}>优化提示词</Button>
                            </Col>
                        </Row>
                    </Form.Item>

                    <Form.Item label="热点问题" style={{ width: '100%', marginBottom: 8 }}>
                        <Row gutter={[16, 16]}>
                            {this.getQuestionInputFields()}
                            {assistantInfo?.sysShare ? null : (
                                <Col span={8}>
                                    <Button icon="plus" onClick={this.getAddQuestionInput}>添加</Button>
                                </Col>
                            )}
                        </Row>
                    </Form.Item>

                    <Form.Item label="大模型选择" style={{ width: '75%', marginBottom: 8 }}>
                        <Row gutter={[16, 16]}>
                            {this.getModelSelectFields()}
                            {/* {assistantInfo?.sysShare ? null : (
                                <Col span={8}>
                                    <Button icon="plus" onClick={this.getAddModelSelect}>添加</Button>
                                </Col>
                            )} */}
                        </Row>
                    </Form.Item>
                </Form>
            </Modal >
        );
    }

    getAddQuestionInput = () => {
        let { questionCount } = this.state;
        questionCount = questionCount + 1;
        this.setState({ questionCount })
    }

    delQuestionInput = count => {
        const { form } = this.props;
        let { questionCount } = this.state;
        let questions = form.getFieldValue("questionList");
        console.log(questions);
        let questionList = [...questions].filter((_, index) => index != count);
        console.log(questionList);
        form.setFieldsValue({ questionList });
        questionCount = questionCount - 1;
        this.setState({ questionCount })
    }

    getQuestionInputFields = () => {
        const { questionCount, assistantInfo } = this.state;
        const { getFieldDecorator } = this.props.form;
        const children = [];
        for (let i = 0; i < questionCount; i++) {
            children.push(
                <Col span={8}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
                        {getFieldDecorator(`questionList[${i}]`, { initialValue: assistantInfo?.questionList[i] })(<Input />)}
                        {assistantInfo?.sysShare ? null : <Icon type="close" onClick={() => this.delQuestionInput(i)} />}
                    </div>
                </Col>
            );
        };
        return children;
    }

    getAddModelSelect = () => {
        let { modelCount } = this.state;
        modelCount = modelCount + 1;
        this.setState({ modelCount })
    }

    delModelSelect = count => {
        const { form } = this.props;
        let { modelCount } = this.state;
        let modelIds = form.getFieldValue("modelIdList");
        console.log(modelIds);
        let modelIdList = [...modelIds].filter((_, index) => index != count);
        console.log(modelIdList);
        form.setFieldsValue({ modelIdList });
        modelCount = modelCount - 1;
        this.setState({ modelCount })
    }

    getModelSelectFields = () => {
        const { modelCount, modelList, assistantInfo } = this.state;
        const { getFieldDecorator } = this.props.form;
        const children = [];
        for (let i = 0; i < modelCount; i++) {
            children.push(
                <Col span={8}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
                        {assistantInfo?.sysShare ? (
                            <>{getFieldDecorator(`modelIdList[${i}]`, { initialValue: assistantInfo?.modelList[i].name })(<Input  />)}</>
                        ) : (
                            <>
                                {getFieldDecorator(`modelIdList[${i}]`, { initialValue: assistantInfo?.modelIdList[i] })(
                                    <Select>
                                        {modelList.map((item, index) => (
                                            <Select.Option value={item.id} key={index}>{item.name}</Select.Option>
                                        ))}
                                    </Select>
                                )}
                            </>
                        )}
                        {/* {assistantInfo?.sysShare ? null : <Icon type="close" onClick={() => this.delModelSelect(i)} />} */}
                    </div>
                </Col>
            );
        };
        return children;
    }

    normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };

    handleChangeImage = (file, type) => {
        if (file.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        };
        if (file.file.status === "done") {
            this.setState({
                [type]: file.file.response.url,
                loading: false,
            });
        }
    };

    /**
     * 上传图片前判断
     * @returns {*}
     */
    beforeUpload = (file) => {
        let b = /\.(png|jpg|gif|svg)$/;
        let a = file.name.toLowerCase();

        const pig = b.test(a);
        const isJPG = file.type;
        const isLt2M = file.size / 1024 / 1024 < 200;

        if (!pig) {
            if (!isLt2M) {
                message.error("请上传小于2M的图片");
            } else {
                message.error("请上传图片格式");
            }
        } else {
            if (!isLt2M) {
                message.error("请上传小于2M的图片");
            }
        };
        return isJPG && isLt2M && pig;
    };

    setImgUrl = (row, type) => {
        this.setState({ [type]: row.url });
    }


    getGenerateQuestion = async () => {
        const { form } = this.props;
        this.setState({ generateLoading: true }, async () => {
            let obj, res = { code: -1, data: false, mag: "操作失败" };
            let formInfo = form.getFieldsValue();
            obj = { content: formInfo.characterSetting };
            let modelIdList = formInfo.modelIdList.filter(item => item);
            if (modelIdList && modelIdList.length > 0) {
                obj.modelId = modelIdList[0];
                res = await postGenerateSettings(obj);
            } else {
                this.setState({ generateLoading: false });
                return message.error('请选择至少一个大模型！！');
            };
            console.log(res);
            if (res.code === 0) {
                form.setFieldsValue({ characterSetting: res.data })
                this.setState({ generateLoading: false });
                message.success('生成成功');
            }
        })
    }

}

export default Form.create()(AddAgent);
